package com.itheima.aop;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

@Aspect
@Component
@Slf4j
public class LogAspect {
    @Autowired
    private HttpServletRequest request;//被IOC容器管理了，可以直接注入使用

    @Autowired
    private OperateLogMapper logMapper;

    @Around("@annotation(com.itheima.anno.Log)")
    public Object logRecord(ProceedingJoinPoint joinPoint) throws Throwable {
        log.warn(joinPoint.getTarget().getClass().getName()+"."+joinPoint.getSignature().getName()+"正在执行！！");

        long t1 = System.currentTimeMillis();
        Object result = joinPoint.proceed();//目标方法的调用
        long t2 = System.currentTimeMillis();



        //获取token,在token中存在用户的id
        String tokenJwt = request.getHeader("token");



        Integer operateUser = (Integer) JwtUtils.parseJWT(tokenJwt).get("id"); //操作人
        LocalDateTime operateTime = LocalDateTime.now(); //操作时间
        String className = joinPoint.getTarget().getClass().getName(); //操作类名
        String methodName = joinPoint.getSignature().getName(); //操作方法名
        String methodParams = Arrays.toString(joinPoint.getArgs()); //操作方法参数
        //String returnValue = new ObjectMapper().writeValueAsString(result); //操作方法返回值 Jackson
        String returnValue = JSON.toJSONString(result); //操作方法返回值 Alibaba
        Long costTime = t2-t1; //操作耗时
        //将数据封装到对象中
        OperateLog operateLog = OperateLog.builder()
                .operateUser(operateUser)
                .operateTime(operateTime)
                .className(className)
                .methodName(methodName)
                .methodParams(methodParams)
                .returnValue(returnValue)
                .costTime(costTime)
                .build();
        //将对象映射到数据库中
        logMapper.insert(operateLog);

        return result;
    }

}
